package com.example.person;

import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 其实相当于是个配置类的角色
 */
@RestController
@Configuration

public class PersonController {

    @Autowired
    private DiscoveryClient discoveryClient;

    //调用rest 服务的类  就具有负载均衡的功能了
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @RequestMapping(value = "/router")
    public String router(){
        RestTemplate template=getRestTemplate();
        String json=template.getForObject("http://spring-lb-provider/call/1",String.class);
        return json;
    }

    @GetMapping("/list")

    public String sercieCount(){
        List<String>names=discoveryClient.getServices();
        //根据服务id获取服务实例
        for (String serviceId:names){
            List<ServiceInstance>instances=discoveryClient.getInstances(serviceId);
            System.out.println(serviceId+": "+instances.size());
        }
        return "";
    }

    @GetMapping("/getMetadata")
    public String getMetadata(){
        List<ServiceInstance>instances=discoveryClient.getInstances("client");
        for (ServiceInstance instance:instances){
            String name=instance.getMetadata().get("company-name");
            System.out.println(instance.getPort()+"=="+name);
        }
        return "";

    }




}
